<template>
	<view class="pb-safe-area">
		<view class="p-4 flex flex-column grid-gap-6">
			<view class="bg-white rounded-4 p-4 flex flex-column grid-gap-6">
				<view class="flex flex-center grid-gap-2" @tap="chooseLocation" v-if="showSelectMap">
					<view class="w-100px text-primary h9 font-weight-600">在地图上选择</view>
					<view class="flex-1"></view>
					<uni-icons type="location-filled" size="20" color="var(--xl-primary)"></uni-icons>
				</view>
				<view class="flex flex-center grid-gap-2" @tap="openRegions">
					<view class="w-100px text-grey h9">选择地区</view>
					<view class="flex-1">
						<view class="uni-input-wrapper">
							<text v-if="form.province_id">{{ form.province }} {{ form.city }} {{ form.area }}
								{{ form.street }}</text>
							<text class="uni-input-placeholder input-placeholder" v-else>选择地区</text>
						</view>
					</view>
					<uni-icons type="right" color="var(--xl-placeholder)"></uni-icons>
				</view>
				<view class="flex flex-center grid-gap-2">
					<view class="w-100px text-grey h9">详细地址</view>
					<textarea class="flex-1" v-model="form.address_detail" auto-height maxlength="200"
						placeholder-class="text-placeholder" placeholder="详细地址，例如：XX小区X栋X单元X楼8888号"></textarea>
				</view>
				<view class="flex flex-center grid-gap-2">
					<view class="w-100px text-grey h9">联系人</view>
					<view class="flex-1">
						<input type="text" placeholder="请输入联系人" v-model="form.name"
							placeholder-class="text-placeholder">
					</view>
				</view>
				<view class="flex flex-center grid-gap-2">
					<view class="w-100px text-grey h9">联系电话</view>
					<view class="flex-1">
						<input type="tel" placeholder="请输入联系电话" v-model="form.mobile" maxlength="11"
							placeholder-class="text-placeholder">
					</view>
				</view>
				<view class="flex flex-center grid-gap-2">
					<view class="w-100px text-grey h9">设为默认</view>
					<view class="flex-1"></view>
					<switch :checked="form.is_default === 1" @change="form.is_default = $event.detail.value ? 1 : 0"
						color="var(--xl-primary)" style="transform: scale(0.7);">
					</switch>
				</view>
			</view>

			<view class="flex">
				<button class="btn-primary btn-round flex-1" @tap="submit()">保存</button>
			</view>
		</view>
		<x-regions ref="xRegionsRef" @selected="selectedRegions" />
		<x-loading v-if="loading" />
	</view>
</template>

<script setup lang="ts">
import { ref, nextTick, watchEffect } from "vue";
import { $api, $message, $page,useStorage,$helper } from "@/utils";
import { onLoad, onUnload } from '@dcloudio/uni-app';
import { $EventName } from "@/utils/const/env";
import { useWebConfigStore, useRefs } from "@/stores";
const WebConfigStore = useWebConfigStore();
const { WEBCONFIG } = useRefs(WebConfigStore);
const showSelectMap = ref(true);
// #ifdef H5 || MP-WEIXIN
watchEffect(() => {
	// #ifdef H5
	showSelectMap.value = WEBCONFIG.value?.amap_web_key ? true : false;
	// #endif
	// #ifdef MP-WEIXIN
	showSelectMap.value = WEBCONFIG.value?.amap_mini_key ? true : false;
	// #endif
})
// #endif
const storeage = useStorage();
const loading = ref(false);
const form = ref({
	id: '',
	province_id: '',
	province: '',
	city_id: '',
	city: '',
	area_id: '',
	area: '',
	street_id: '',
	street: '',
	address_detail: '',
	name: '',
	mobile: '',
	is_default: 0,
	latitude: 0,
	longitude: 0,
});
const submit = () => {
	if(!form.value.latitude||!form.value.longitude){
		uni.showModal({
			content: '还未在地图上选择地址，是否立即选择',
			success: (res:any) => {
				if (res.confirm) {
					chooseLocation();
				}
			}
		})
		return;
	}
	uni.showLoading({ title: '保存中...' });
	$api.Address.saveAddress(form.value).then((res: any) => {
		uni.hideLoading();
		$message.success(res.msg);
		nextTick(() => {
			$page.back();
		});
	}).catch((err: any) => {
		uni.hideLoading();
		$message.error(err.msg);
	})
}
const xRegionsRef = ref();
const openRegions = () => {
	xRegionsRef.value?.show();
}
const selectedRegions = (regions: any) => {
	if (regions.province_id) {
		form.value.province_id = regions.province_id;
		form.value.province = regions.province;
	} else {
		form.value.province_id = '';
		form.value.province = '';
	}
	if (regions.city_id) {
		form.value.city_id = regions.city_id;
		form.value.city = regions.city;
	} else {
		form.value.city_id = '';
		form.value.city = '';
	}
	if (regions.area_id) {
		form.value.area_id = regions.area_id;
		form.value.area = regions.area;
	} else {
		form.value.area_id = '';
		form.value.area = '';
	}
	if (regions.street_id) {
		form.value.street_id = regions.street_id;
		form.value.street = regions.street;
	} else {
		form.value.street_id = '';
		form.value.street = '';
	}
}

const EventNameCHOOSE_LOCATION = `UserAddressSaveChooseLocation${$EventName.CHOOSE_LOCATION}`;
const chooseLocation = () => {
	uni.chooseLocation({
		success: (res: any) => {
			form.value.address_detail = res.address;
			updateLocation(res);
		}
	})
}
const updateLocation = (res: any) => {
	form.value.latitude = res.latitude;
	form.value.longitude = res.longitude;
	loading.value = true;
	$api.Map.regeo({
		lnglat: [res.longitude, res.latitude]
	}).then((res: any) => {
		let data = res.data;
		// const formattedAddress = data.formatted_address;
		const addressComponent = data.addressComponent;
		/* data.desc = formattedAddress
			.replace(addressComponent.province + addressComponent.city + addressComponent.district + addressComponent.township, ''); */
		// form.value.address_detail = data.desc;
		xRegionsRef.value.search({
			province:addressComponent.province,
			city:addressComponent.city||addressComponent.province,
			area:addressComponent.district,
			street:addressComponent.township
		})
	}).catch((err: any) => {
		$message.error(err.msg);
	}).finally(() => {
		loading.value = false;
	})
}

onLoad((options: any) => {
	const appid = $helper.appid();
	if (options.id) {
		loading.value = true;
		$api.Address.getAddressDetails(options.id).then((data: any) => {
			form.value = data;
		}).finally(() => {
			loading.value = false;
		});
	}else if(storeage.get('CHANNELS_ID.' + appid)){
		loading.value = true;
		$api.Channels.getAddress().then((data:any)=>{
			form.value=data;
		}).catch(()=>{
		}).finally(()=>{
			loading.value = false;
		})
	}
	uni.$on(EventNameCHOOSE_LOCATION, updateLocation)
})
onUnload(() => {
	uni.$off(EventNameCHOOSE_LOCATION, updateLocation)
});
</script>

<style lang="scss" scoped>
.map-container {
	padding: 0px;
	margin: 0px;
	width: 100%;
	height: 50vh;
}

.w-100px {
	width: 100px;
}
</style>
